import smtplib

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

from sqlalchemy import event
from inqueue.models import *

class SMS(object):

  T_MOBILE = "T-Mobile"
  VERIZON = "Verizon"
  ATT = "AT&T"

  SMS_GATEWAYS = {
    T_MOBILE: "tmomail.net",
    VERIZON: "vtext.com",
    ATT: "txt.att.net"
  }

  @staticmethod
  def get_sms_email(phone_number, carrier):
    if carrier == SMS.T_MOBILE:
      return "1{0}@{1}".format(phone_number, SMS.SMS_GATEWAYS.get(carrier))
    else:
      return "{0}@{1}".format(phone_number, SMS.SMS_GATEWAYS.get(carrier))

  @staticmethod
  def send_text(phone_number, carrier):
    m = MultipartMail(
      recipients=[SMS.get_sms_email(phone_number, carrier)],
      text_body="Your order is ready! ",
      html_body="Your order is ready",
    )
    m.send()



class MultipartMail(object):

  def __init__(self, recipients, subject, html_body, text_body):
    self.msg = MIMEMultipart('alternative')
    self.msg['Subject'] = subject
    self.msg['From'] = 'inqueuerobot'
    self.msg['To'] = ','.join(recipients) if recipients else ''
    self.recipients = recipients

    part1 = MIMEText(html_body, 'plain')
    part2 = MIMEText(text_body, 'html')

    self.msg.attach(part1)
    self.msg.attach(part2)

  def send(self):
    gmail_user = 'inqueuerobot'
    gmail_pwd = 'linkedin'
    server = smtplib.SMTP("smtp.gmail.com", 587)
    server.ehlo()
    server.starttls()
    server.ehlo()
    server.login(gmail_user, gmail_pwd)
    server.sendmail(gmail_user, self.recipients, self.msg.as_string())
    # Should be server.quit(), but that crashes...
    server.close()


if __name__ == '__main__':
  m = MultipartMail(
    recipients=['14057623336@tmomail.net'],
    subject='subject', text_body='text', html_body='html'
  )
  m.send()